package com.dotflat.fin.service.impl;

import com.dotflat.fin.PO.FinPayAccountPO;
import com.dotflat.fin.domain.FinPayAccount;
import com.dotflat.fin.repository.FinPayAccountRepository;
import com.dotflat.fin.service.FinPayAccountService;
import com.dotflat.rest.PO.AreableObjectBasePO;
import com.dotflat.rest.service.impl.AreableObjectBaseServiceImpl;
import com.matt.commons.exception.BusinessException;
import com.matt.foundation.model.ErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单信息service
 *
 * @author ：Ron
 * @date ：Created in 2020/10/30 13:06
 */
@Service
public class FinPayAccountServiceImpl extends AreableObjectBaseServiceImpl<FinPayAccount, FinPayAccountRepository> implements FinPayAccountService {

    @Override
    @Autowired
    public void setBaseRepository(FinPayAccountRepository baseRepository) {
        super.setBaseRepository(baseRepository);
    }

    @Override
    public FinPayAccount activedPayAccount(String areaId, Integer payType){
        List<FinPayAccount> accounts = baseRepository.findAllByAreaIdAndDeletedIsFalseAndAccountTypeAndEnabledIsTrue(areaId, payType);

        if (accounts == null || accounts.size() == 0){
            return null;
        }
        if (accounts.size() > 1){
            throw new BusinessException(ErrorCode.VERSION_ERROR, "不能同时启用多个收款账号");
        }

        return accounts.get(0);
    }

    @Override
    @Transactional(rollbackOn = RuntimeException.class)
    public FinPayAccount add(String areaId, String staffId, AreableObjectBasePO param) {
        // 需要处理多账号的enable开关逻辑, 打开一个,其他都要关闭
        if (param instanceof FinPayAccountPO){
            FinPayAccountPO po = ((FinPayAccountPO) param);
            if (po.getEnabled()){
                List<FinPayAccount> accounts = baseRepository.findAllByAreaIdAndDeletedIsFalseAndAccountTypeAndEnabledIsTrue(areaId, po.getAccountType());

                List<FinPayAccount> toSave = accounts.stream().filter(o->{
                    if (o.getId().equals(param.getId())){
                        //过滤掉当前变更的这个.
                        return false;
                    }
                    boolean ret = o.getEnabled();
                    if (ret){
                        //关闭其他打开的
                        o.setEnabled(false);
                    }
                    return ret;
                }).collect(Collectors.toList());
                if (toSave != null && toSave.size() > 0) {
                    baseRepository.saveAll(toSave);
                }
            }
        }

        return add(areaId, staffId, param, null);
    }

}
